import { login, logout, getUserInfo } from '@/api/user'
import { rights, menus } from '@/api/permission'
import { getToken, setToken, removeToken, getId, setId, removeId } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    permission: []
  }
}

function generatePermission(arrObj) {
  const arr = []
  arrObj.forEach(one => {
    arr.push(one.path + '_' + one.id + '_01')
    if (one.hasOwnProperty('children')) {
      one.children.forEach(two => {
        arr.push(two.path + '_' + two.id + '_02')
        if (two.hasOwnProperty('children')) {
          two.children.forEach(three => {
            arr.push(three.path + '_' + three.id + '_03')
          })
        }
      })
    }
  })

  return arr
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        commit('SET_TOKEN', response.token)
        commit('SET_NAME', response.username)
        setToken(response.token)
        setId(response.id)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user prmission
  getPermission({ commit, state }) {
    return new Promise((resolve, reject) => {
      rights('tree').then(response => {
        console.log('permission::', response)
        const permission = generatePermission(response)
        commit('SET_PERMISSION', permission)
        resolve(permission)
      }).catch(error => {
        reject(error)
      })
      menus().then(res => {
        console.log('menus:::', res)
      })
    })
  },

  // get user info
  async getUserInfo({ commit }) {
    const id = getId()
    const { username } = await getUserInfo(id)
    commit('SET_NAME', username)
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      removeToken()
      removeId()
      resetRouter()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

